package com.hu.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hu.common.exception.ServiceException;
import com.hu.common.utils.SecurityUtils;
import com.hu.system.domain.ProductInfo;
import com.hu.system.domain.PurchaseInbound;
import com.hu.system.domain.StockInbound;
import com.hu.system.mapper.ProductInfoMapper;
import com.hu.system.mapper.PurchaseInboundMapper;
import com.hu.system.mapper.StockInboundMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.service.IPurchaseInboundService;
import com.hu.system.service.IProductInfoService;
import com.hu.common.utils.StringUtils;

/**
 * 采购入库Service业务层处理
 *
 * @author hu
 * @date 2025-01-21
 */
@Service
public class PurchaseInboundServiceImpl implements IPurchaseInboundService {
    @Autowired
    private PurchaseInboundMapper purchaseInboundMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private StockInboundMapper stockInboundMapper;

    @Autowired
    private IProductInfoService productInfoService;

    /**
     * 查询采购入库列表（带数据权限过滤）
     *
     * @param purchaseInbound 采购入库
     * @return 采购入库
     */
    @Override
    public List<PurchaseInbound> selectPurchaseInboundList(PurchaseInbound purchaseInbound) {
        Long userId = SecurityUtils.getUserId();

        // 管理员查看全部采购记录
        if (userId != null && userId == 1L) {
            return purchaseInboundMapper.selectPurchaseInboundList(purchaseInbound);
        }

        // 普通用户根据绑定的店铺过滤采购记录
        // 保存分页参数（因为查询店铺ID会消耗分页参数）
        com.github.pagehelper.Page<?> page = PageHelper.getLocalPage();
        // 清除分页参数，让店铺ID查询不使用分页
        PageHelper.clearPage();
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        // 恢复分页参数，让主查询使用分页
        if (page != null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize(), page.getOrderBy());
        }
        if (shopIds == null || shopIds.isEmpty()) {
            // 用户未绑定任何店铺，返回空列表
            return new ArrayList<>();
        }

        // 设置店铺ID过滤条件
        Map<String, Object> params = purchaseInbound.getParams();
        if (params == null) {
            params = new HashMap<>();
            purchaseInbound.setParams(params);
        }
        params.put("shopIdList", shopIds);

        return purchaseInboundMapper.selectPurchaseInboundList(purchaseInbound);
    }

    /**
     * 查询采购入库（带数据权限校验）
     *
     * @param inboundId 采购入库主键
     * @return 采购入库
     */
    @Override
    public PurchaseInbound selectPurchaseInboundByInboundId(Long inboundId) {
        PurchaseInbound inbound = purchaseInboundMapper.selectPurchaseInboundByInboundId(inboundId);
        if (inbound == null) {
            return null;
        }

        Long userId = SecurityUtils.getUserId();

        // 管理员可查看全部
        if (userId != null && userId == 1L) {
            return inbound;
        }

        // 普通用户校验是否有权限查看该采购记录
        List<Long> userShopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (userShopIds == null || !userShopIds.contains(inbound.getShopId())) {
            return null;
        }

        return inbound;
    }

    /**
     * 统计采购数据（带数据权限过滤）
     *
     * @param purchaseInbound 采购入库查询条件
     * @return 统计结果
     */
    @Override
    public com.hu.system.domain.PurchaseStatistics selectPurchaseStatistics(PurchaseInbound purchaseInbound) {
        Long userId = SecurityUtils.getUserId();

        // 管理员查看全部采购统计
        if (userId != null && userId == 1L) {
            return purchaseInboundMapper.selectPurchaseStatistics(purchaseInbound);
        }

        // 普通用户根据绑定的店铺过滤采购统计
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (shopIds == null || shopIds.isEmpty()) {
            // 用户未绑定任何店铺，返回空统计
            com.hu.system.domain.PurchaseStatistics emptyStats = new com.hu.system.domain.PurchaseStatistics();
            emptyStats.setTotalAmount(BigDecimal.ZERO);
            emptyStats.setTotalQuantity(0L);
            emptyStats.setTotalRecords(0L);
            emptyStats.setAvgUnitPrice(BigDecimal.ZERO);
            return emptyStats;
        }

        // 设置店铺ID过滤条件
        Map<String, Object> params = purchaseInbound.getParams();
        if (params == null) {
            params = new HashMap<>();
            purchaseInbound.setParams(params);
        }
        params.put("shopIdList", shopIds);

        return purchaseInboundMapper.selectPurchaseStatistics(purchaseInbound);
    }

    /**
     * 新增采购入库
     *
     * @param purchaseInbound 采购入库
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPurchaseInbound(PurchaseInbound purchaseInbound) {
        // 自动获取产品名称和所属店铺（从产品信息中关联）
        if (purchaseInbound.getSku() != null && !purchaseInbound.getSku().isEmpty()) {
            ProductInfo product = productInfoMapper.selectProductInfoBySku(purchaseInbound.getSku());
            if (product != null) {
                purchaseInbound.setProductName(product.getProductName());
                purchaseInbound.setShopId(product.getShopId()); // 从产品中获取店铺ID
            }
        }

        // 自动计算单价：unit_price = purchase_amount / purchase_quantity + package_fee
        calculateUnitPrice(purchaseInbound);

        purchaseInbound.setDelFlag("0");
        purchaseInbound.setCreateBy(SecurityUtils.getUsername());

        // 插入采购记录
        int result = purchaseInboundMapper.insertPurchaseInbound(purchaseInbound);

        // 同步插入库存入库记录
        if (result > 0) {
            StockInbound stockInbound = new StockInbound();
            stockInbound.setSku(purchaseInbound.getSku());
            stockInbound.setProductName(purchaseInbound.getProductName());
            stockInbound.setShopId(purchaseInbound.getShopId());
            stockInbound.setInboundQuantity(purchaseInbound.getPurchaseQuantity());
            stockInbound.setInboundType("PURCHASE");
            stockInbound.setSourceId(purchaseInbound.getInboundId()); // 关联采购记录ID
            stockInbound.setInboundDate(purchaseInbound.getPurchaseDate());
            stockInbound.setRemark("采购入库：" + (purchaseInbound.getRemark() != null ? purchaseInbound.getRemark() : ""));
            stockInbound.setDelFlag("0");
            stockInbound.setCreateBy(SecurityUtils.getUsername());

            stockInboundMapper.insertStockInbound(stockInbound);
        }

        return result;
    }

    /**
     * 修改采购入库（带数据权限校验）
     *
     * @param purchaseInbound 采购入库
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePurchaseInbound(PurchaseInbound purchaseInbound) {
        Long userId = SecurityUtils.getUserId();

        // 管理员可修改全部
        if (userId == null || userId != 1L) {
            // 普通用户只能修改绑定店铺的采购记录
            PurchaseInbound existInbound = selectPurchaseInboundByInboundId(purchaseInbound.getInboundId());
            if (existInbound == null) {
                throw new ServiceException("您没有权限修改该采购记录");
            }
        }

        // 自动获取产品名称和所属店铺（从产品信息中关联）
        if (purchaseInbound.getSku() != null && !purchaseInbound.getSku().isEmpty()) {
            ProductInfo product = productInfoMapper.selectProductInfoBySku(purchaseInbound.getSku());
            if (product != null) {
                purchaseInbound.setProductName(product.getProductName());
                purchaseInbound.setShopId(product.getShopId()); // 从产品中获取店铺ID
            }
        }

        // 自动计算单价
        calculateUnitPrice(purchaseInbound);

        purchaseInbound.setUpdateBy(SecurityUtils.getUsername());

        // ✅ 重要：在更新前先查询原始数据，用于后续匹配孤立的库存记录
        PurchaseInbound originalData = purchaseInboundMapper.selectPurchaseInboundByInboundId(purchaseInbound.getInboundId());

        // 更新采购记录
        int result = purchaseInboundMapper.updatePurchaseInbound(purchaseInbound);

        // 同步更新库存入库记录（兼容新旧数据）
        if (result > 0) {
            // 准备更新数据
            StockInbound stockInbound = new StockInbound();
            stockInbound.setSourceId(purchaseInbound.getInboundId());
            stockInbound.setInboundType("PURCHASE");
            stockInbound.setSku(purchaseInbound.getSku());
            stockInbound.setProductName(purchaseInbound.getProductName());
            stockInbound.setShopId(purchaseInbound.getShopId());
            stockInbound.setInboundQuantity(purchaseInbound.getPurchaseQuantity());
            stockInbound.setInboundDate(purchaseInbound.getPurchaseDate());
            stockInbound.setRemark("采购入库：" + (purchaseInbound.getRemark() != null ? purchaseInbound.getRemark() : ""));
            stockInbound.setUpdateBy(SecurityUtils.getUsername());

            // 先尝试通过 source_id 更新（新数据）
            int updateCount = stockInboundMapper.updateStockInboundBySourceId(stockInbound);

            // 如果没有更新任何记录，说明可能是旧数据（source_id 为空），尝试智能匹配
            if (updateCount == 0 && originalData != null) {
                // 使用更新前的原始数据在 SQL 层面精确匹配孤立的库存记录
                // 避免内存中遍历所有孤立记录，提升性能
                StockInbound orphan = stockInboundMapper.selectOrphanStockInboundByOriginalData(
                    "PURCHASE",
                    originalData.getSku(),                // 使用修改前的原始SKU
                    originalData.getPurchaseQuantity(),   // 使用修改前的原始数量
                    originalData.getPurchaseDate(),       // 使用修改前的原始日期
                    originalData.getCreateBy()            // 使用原始创建人
                );

                if (orphan != null) {
                    // 找到匹配的孤立记录，建立关联并更新为新数据
                    orphan.setSourceId(purchaseInbound.getInboundId());
                    orphan.setSku(purchaseInbound.getSku());
                    orphan.setProductName(purchaseInbound.getProductName());
                    orphan.setShopId(purchaseInbound.getShopId());
                    orphan.setInboundQuantity(purchaseInbound.getPurchaseQuantity());
                    orphan.setInboundDate(purchaseInbound.getPurchaseDate());
                    orphan.setRemark("采购入库：" + (purchaseInbound.getRemark() != null ? purchaseInbound.getRemark() : ""));
                    orphan.setUpdateBy(SecurityUtils.getUsername());

                    stockInboundMapper.updateStockInbound(orphan);
                }
            }
        }

        return result;
    }

    /**
     * 批量删除采购入库（带数据权限校验）
     *
     * @param inboundIds 需要删除的采购入库主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePurchaseInboundByInboundIds(Long[] inboundIds) {
        Long userId = SecurityUtils.getUserId();

        // 管理员可删除全部
        if (userId == null || userId != 1L) {
            // 普通用户只能删除绑定店铺的采购记录
            for (Long inboundId : inboundIds) {
                PurchaseInbound inbound = selectPurchaseInboundByInboundId(inboundId);
                if (inbound == null) {
                    throw new ServiceException("您没有权限删除部分采购记录");
                }
            }
        }

        // 删除采购记录
        int result = purchaseInboundMapper.deletePurchaseInboundByInboundIds(inboundIds);

        // 同步删除对应的库存入库记录
        if (result > 0) {
            stockInboundMapper.deleteStockInboundBySourceIds(inboundIds);
        }

        return result;
    }

    /**
     * 计算产品单价
     * 公式：unit_price = purchase_amount / purchase_quantity + package_fee
     *
     * @param purchaseInbound 采购入库对象
     */
    private void calculateUnitPrice(PurchaseInbound purchaseInbound) {
        if (purchaseInbound.getPurchaseAmount() != null
                && purchaseInbound.getPurchaseQuantity() != null
                && purchaseInbound.getPurchaseQuantity() > 0) {
            // 采购金额 ÷ 采购数量
            BigDecimal avgPrice = purchaseInbound.getPurchaseAmount()
                    .divide(new BigDecimal(purchaseInbound.getPurchaseQuantity()), 2, RoundingMode.HALF_UP);

            // 加上单品包装费
            BigDecimal packageFee = purchaseInbound.getPackageFee();
            if (packageFee == null) {
                packageFee = BigDecimal.ZERO;
            }

            BigDecimal unitPrice = avgPrice.add(packageFee);
            purchaseInbound.setUnitPrice(unitPrice);
        }
    }

    /**
     * 判断两个日期是否是同一天
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 是否同一天
     */
    private boolean isSameDay(java.util.Date date1, java.util.Date date2) {
        if (date1 == null || date2 == null) {
            return false;
        }
        java.util.Calendar cal1 = java.util.Calendar.getInstance();
        cal1.setTime(date1);
        java.util.Calendar cal2 = java.util.Calendar.getInstance();
        cal2.setTime(date2);
        
        return cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)
            && cal1.get(java.util.Calendar.DAY_OF_YEAR) == cal2.get(java.util.Calendar.DAY_OF_YEAR);
    }

    /**
     * 导入采购入库数据
     *
     * @param purchaseInboundList 采购入库列表
     * @param updateSupport       是否更新支持
     * @param shopId              所属店铺ID
     * @return 导入结果消息
     */
    @Override
    @Transactional
    public String importPurchaseInbound(List<PurchaseInbound> purchaseInboundList, boolean updateSupport, Long shopId) {
        if (purchaseInboundList == null || purchaseInboundList.isEmpty()) {
            throw new ServiceException("导入数据不能为空");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();

        // 用于批量插入的列表
        List<PurchaseInbound> batchInsertList = new ArrayList<>();

        // 导入备注标识
        String importRemark = "【导入于 " + com.hu.common.utils.DateUtils.getTime() + "】";

        // 本批次已处理的SKU集合，避免重复插入product_info
        java.util.Set<String> processedSkus = new java.util.HashSet<>();

        // 记录产品操作统计
        int createdProductCount = 0;
        int updatedProductCount = 0;
        java.util.List<String> updatedProductDetails = new java.util.ArrayList<>();

        // 第一步：数据校验和预处理（边处理边插入，减少内存占用）
        int batchSize = 100;  // 减小批次到100条，更频繁地释放内存
        
        for (PurchaseInbound purchaseInbound : purchaseInboundList) {
            try {
                // 校验必填字段：SKU
                if (StringUtils.isEmpty(purchaseInbound.getSku())) {
                    failureNum++;
                    failureMsg.append("<br/>第" + (successNum + failureNum) + "条：SKU编码不能为空");
                    continue;
                }

                // 校验必填字段：采购数量
                if (purchaseInbound.getPurchaseQuantity() == null || purchaseInbound.getPurchaseQuantity() <= 0) {
                    failureNum++;
                    failureMsg.append("<br/>SKU[" + purchaseInbound.getSku() + "]：采购数量不能为空且必须大于0");
                    continue;
                }

                // 校验必填字段：采购总金额
                if (purchaseInbound.getPurchaseAmount() == null || purchaseInbound.getPurchaseAmount().compareTo(BigDecimal.ZERO) <= 0) {
                    failureNum++;
                    failureMsg.append("<br/>SKU[" + purchaseInbound.getSku() + "]：采购总金额不能为空且必须大于0");
                    continue;
                }

                // 校验必填字段：采购入库日期
                if (purchaseInbound.getPurchaseDate() == null) {
                    failureNum++;
                    failureMsg.append("<br/>SKU[" + purchaseInbound.getSku() + "]：采购入库日期不能为空");
                    continue;
                }

                // 处理包装费：Excel中是总包装费，需要除以采购数量得到单品包装费
                if (purchaseInbound.getPackageFee() == null) {
                    purchaseInbound.setPackageFee(BigDecimal.ZERO);
                } else {
                    // 总包装费 ÷ 采购数量 = 单品包装费
                    BigDecimal totalPackageFee = purchaseInbound.getPackageFee();
                    BigDecimal unitPackageFee = totalPackageFee.divide(
                        new BigDecimal(purchaseInbound.getPurchaseQuantity()), 
                        2, 
                        RoundingMode.HALF_UP
                    );
                    purchaseInbound.setPackageFee(unitPackageFee);
                }

                // 检查产品是否存在，不存在则自动创建，存在则更新（使用用户选择的店铺）
                // 同一批次中相同SKU只处理一次，避免唯一键冲突
                ProductInfo product = null;
                if (!processedSkus.contains(purchaseInbound.getSku())) {
                    com.hu.system.domain.ProductOperationResult operationResult = productInfoService.getOrCreateProduct(
                            purchaseInbound.getSku(),
                            purchaseInbound.getProductName(),
                            purchaseInbound.getSkuAttr(),
                            null,  // skuCode为空时服务层会自动设置为sku
                            shopId
                    );
                    product = operationResult.getProduct();
                    processedSkus.add(purchaseInbound.getSku());

                    // 如果导入数据中包含平台核价，则更新产品的核价字段
                    if (purchaseInbound.getPriceCheck() != null && purchaseInbound.getPriceCheck().compareTo(BigDecimal.ZERO) > 0) {
                        product.setPriceCheck(purchaseInbound.getPriceCheck());
                        product.setUpdateBy(SecurityUtils.getUsername());
                        productInfoMapper.updateProductInfo(product);

                        // 标记为更新操作
                        if (operationResult.getOperationType() == com.hu.system.domain.ProductOperationResult.OperationType.CREATED) {
                            updatedProductDetails.add("SKU[" + purchaseInbound.getSku() + "] 新建并设置核价");
                        } else {
                            updatedProductDetails.add("SKU[" + purchaseInbound.getSku() + "] 更新核价");
                        }
                    }

                    // 统计产品操作
                    if (operationResult.getOperationType() == com.hu.system.domain.ProductOperationResult.OperationType.CREATED) {
                        createdProductCount++;
                    } else if (operationResult.getOperationType() == com.hu.system.domain.ProductOperationResult.OperationType.UPDATED) {
                        updatedProductCount++;
                        updatedProductDetails.add("SKU[" + purchaseInbound.getSku() + "]" + operationResult.getUpdateDescription());
                    }
                } else {
                    // 本批次已处理过该SKU，从数据库查询产品信息（按SKU和店铺ID查询）
                    product = productInfoService.selectProductInfoBySkuAndShopId(purchaseInbound.getSku(), shopId);
                }

                // 设置店铺ID为用户选择的店铺
                purchaseInbound.setShopId(shopId);

                // 从产品信息中补充字段（如果导入数据中没有）
                if (product != null) {
                    if (StringUtils.isEmpty(purchaseInbound.getProductName())) {
                        purchaseInbound.setProductName(product.getProductName());
                    }
                    if (StringUtils.isEmpty(purchaseInbound.getSkuAttr())) {
                        purchaseInbound.setSkuAttr(product.getSkuAttr());
                    }
                }

                // 自动计算产品单价：unit_price = purchase_amount / purchase_quantity + package_fee
                calculateUnitPrice(purchaseInbound);

                // 添加导入备注标识
                if (StringUtils.isEmpty(purchaseInbound.getRemark())) {
                    purchaseInbound.setRemark(importRemark);
                } else {
                    purchaseInbound.setRemark(purchaseInbound.getRemark() + " " + importRemark);
                }

                // 设置基础字段
                purchaseInbound.setDelFlag("0");
                purchaseInbound.setCreateBy(SecurityUtils.getUsername());

                // 添加到批量插入列表
                batchInsertList.add(purchaseInbound);
                successNum++;
                
                // 关键优化：每达到批次大小就立即插入数据库，同时创建库存记录，然后清空列表释放内存
                if (batchInsertList.size() >= batchSize) {
                    // 先批量插入采购记录（MyBatis会自动回填每个对象的inboundId）
                    purchaseInboundMapper.batchInsertPurchaseInbound(new ArrayList<>(batchInsertList));
                    
                    // 使用自动回填的ID同步创建库存入库记录
                    List<StockInbound> stockInboundList = new ArrayList<>();
                    for (PurchaseInbound pi : batchInsertList) {
                        StockInbound stockInbound = new StockInbound();
                        stockInbound.setSku(pi.getSku());
                        stockInbound.setProductName(pi.getProductName());
                        stockInbound.setShopId(pi.getShopId());
                        stockInbound.setInboundQuantity(pi.getPurchaseQuantity());
                        stockInbound.setInboundType("PURCHASE");
                        stockInbound.setSourceId(pi.getInboundId()); // 使用自动回填的ID
                        stockInbound.setInboundDate(pi.getPurchaseDate());
                        stockInbound.setRemark("采购入库：" + (pi.getRemark() != null ? pi.getRemark() : ""));
                        stockInbound.setDelFlag("0");
                        stockInbound.setCreateBy(SecurityUtils.getUsername());
                        stockInboundList.add(stockInbound);
                    }
                    stockInboundMapper.batchInsertStockInbound(stockInboundList);
                    
                    // 清空列表释放内存
                    batchInsertList.clear();
                    stockInboundList.clear();
                }

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + (successNum + failureNum) + "、SKU[" + purchaseInbound.getSku() + "] 预处理失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }

        // 第二步：插入剩余数据并同步创建库存记录
        if (!batchInsertList.isEmpty()) {
            // 批量插入采购记录（MyBatis会自动回填每个对象的inboundId）
            purchaseInboundMapper.batchInsertPurchaseInbound(batchInsertList);
            
            // 使用自动回填的ID同步创建库存入库记录
            List<StockInbound> stockInboundList = new ArrayList<>();
            for (PurchaseInbound pi : batchInsertList) {
                StockInbound stockInbound = new StockInbound();
                stockInbound.setSku(pi.getSku());
                stockInbound.setProductName(pi.getProductName());
                stockInbound.setShopId(pi.getShopId());
                stockInbound.setInboundQuantity(pi.getPurchaseQuantity());
                stockInbound.setInboundType("PURCHASE");
                stockInbound.setSourceId(pi.getInboundId()); // 使用自动回填的ID
                stockInbound.setInboundDate(pi.getPurchaseDate());
                stockInbound.setRemark("采购入库：" + (pi.getRemark() != null ? pi.getRemark() : ""));
                stockInbound.setDelFlag("0");
                stockInbound.setCreateBy(SecurityUtils.getUsername());
                stockInboundList.add(stockInbound);
            }
            stockInboundMapper.batchInsertStockInbound(stockInboundList);
            
            // 释放内存
            batchInsertList.clear();
            stockInboundList.clear();
        }

        // 第四步：返回结果
        StringBuilder resultMsg = new StringBuilder();

        if (failureNum > 0) {
            resultMsg.append("导入完成！成功 " + successNum + " 条，失败 " + failureNum + " 条");
        } else {
            resultMsg.append("恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }

        // 添加产品操作统计
        if (createdProductCount > 0 || updatedProductCount > 0) {
            resultMsg.append("<br/><br/>【产品处理统计】");
            if (createdProductCount > 0) {
                resultMsg.append("<br/>新建产品：" + createdProductCount + " 个");
            }
            if (updatedProductCount > 0) {
                resultMsg.append("<br/>更新产品：" + updatedProductCount + " 个");
                if (!updatedProductDetails.isEmpty()) {
                    resultMsg.append("<br/>更新详情：");
                    // 只显示前10条更新详情，避免信息过多
                    int displayCount = Math.min(10, updatedProductDetails.size());
                    for (int i = 0; i < displayCount; i++) {
                        resultMsg.append("<br/>  · " + updatedProductDetails.get(i));
                    }
                    if (updatedProductDetails.size() > 10) {
                        resultMsg.append("<br/>  · ... 还有 " + (updatedProductDetails.size() - 10) + " 条更新");
                    }
                }
            }
        }

        if (failureNum > 0) {
            resultMsg.append("<br/><br/>错误如下：");
            resultMsg.append(failureMsg.toString());
            throw new ServiceException(resultMsg.toString());
        } else {
            return resultMsg.toString();
        }
    }
}

